<template>
  <div class="allot-detail-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <el-icon class="header-icon">
            <Box />
          </el-icon>
          <h1 class="page-title">调拨单详情</h1>
        </div>
        <div class="header-right">
          <el-button type="primary" @click="handleOutbound" class="action-btn">
            <el-icon><Upload /></el-icon>
            调出
          </el-button>
          <el-button type="success" @click="handleInbound" class="action-btn">
            <el-icon><Download /></el-icon>
            调入
          </el-button>
          <el-button type="warning" @click="handleCopy" class="action-btn">
            <el-icon><CopyDocument /></el-icon>
            复制
          </el-button>
          <el-button type="info" @click="handlePrint" class="action-btn">
            <el-icon><Printer /></el-icon>
            打印
          </el-button>
        </div>
      </div>
    </div>

    <!-- 订单信息卡片 -->
    <el-card class="order-info-card" shadow="hover">
      <div class="order-info">
        <div class="order-header">
          <h2 class="order-title">调拨单号: {{ orderInfo.movingCode }}</h2>
        </div>
        
        <div class="order-details">
          <div class="details-left">
            <div class="detail-row">
              <span class="label">制单人:</span>
              <span class="value">{{ orderInfo.creatorName }}</span>
            </div>
            <div class="detail-row">
              <span class="label">所在部门:</span>
              <span class="value">{{ orderInfo.department_Name }}</span>
            </div>
            <div class="detail-row">
              <span class="label">制单时间:</span>
              <span class="value">{{ formatDateTime(orderInfo.createTime) }}</span>
            </div>
            <div class="detail-row">
              <span class="label">调拨类型:</span>
              <span class="value">{{ orderInfo.allotWarehouseType }}</span>
            </div>
            <div class="detail-row">
              <span class="label">调拨申请日期:</span>
              <span class="value">{{ formatDate(orderInfo.createTime) }}</span>
            </div>
            <div class="detail-row">
              <span class="label">调出仓库:</span>
              <span class="value">{{ orderInfo.original_OutWarehouse }}</span>
            </div>
            <div class="detail-row">
              <span class="label">调入仓库:</span>
              <span class="value">{{ orderInfo.original_InWarehouse }}</span>
            </div>
            <div class="detail-row">
              <span class="label">经办人:</span>
              <span class="value">{{ orderInfo.reviewer }}</span>
            </div>
            <div class="detail-row">
              <span class="label">备注:</span>
              <span class="value">{{ orderInfo.remarks || '-' }}</span>
            </div>
          </div>
          
          <div class="details-right">
            <div class="status-card">
              <div class="status-item">
                <span class="status-label">单据状态</span>
                <span class="status-value approved">{{ orderInfo.state }}</span>
              </div>
              <div class="status-item">
                <span class="status-label">出库状态</span>
                <span class="status-value">{{ orderInfo.outState }}</span>
                <span class="status-count">{{ orderInfo.outCount }}/{{ orderInfo.totalCount }}</span>
              </div>
              <div class="status-item">
                <span class="status-label">入库状态</span>
                <span class="status-value">{{ orderInfo.inState }}</span>
                <span class="status-count">{{ orderInfo.inCount }}/{{ orderInfo.totalCount }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 标签页导航 -->
    <el-card class="tabs-card" shadow="hover">
      <el-tabs v-model="activeTab" class="detail-tabs">
        <el-tab-pane label="其他信息" name="other">
          <div class="tab-content">
            <p>其他信息内容</p>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="调拨明细" name="details">
          <div class="tab-content">
            
            
            <div class="table-header">
              <el-button type="info" @click="handleExportDetails" class="export-btn">
                <el-icon><Download /></el-icon>
                导出
              </el-button>
            </div>
            
            <el-table
              :data="allocationDetails"
              style="width: 100%"
              border
              stripe
              class="detail-table"
              :summary-method="getSummary"
              show-summary
              v-loading="false"
              :row-key="(row: any, index: number) => index"
            >
              <!-- 调试信息 -->
              <template #empty>
                <div style="padding: 20px; text-align: center;">
                  <p>暂无数据</p>
                  <p>数据长度: {{ allocationDetails.length }}</p>
                  <p>数据类型: {{ typeof allocationDetails }}</p>
                  <p>第一条数据: {{ JSON.stringify(allocationDetails[0]) }}</p>
                </div>
              </template>
              <el-table-column type="selection" width="55" />
              <el-table-column label="序号" width="60">
                <template #default="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="product_Name" label="货品名称" width="120" />
              <el-table-column prop="product_Number" label="货品编号" width="120" />
              <el-table-column prop="specifications" label="规格型号" width="120" />
              <el-table-column prop="unit_Name" label="单位" width="100" />
              <el-table-column prop="category_Name" label="货品类型" width="100" />
              <el-table-column prop="outCount" label="调出仓当前库存" width="150" />
              <el-table-column prop="inCount" label="调入仓当前库存" width="150" />
              <el-table-column prop="allotCount" label="调拨数量" width="100" />
              <el-table-column prop="price" label="调拨单价" width="100">
                <template #default="scope">
                  ¥{{ formatAmount(Number(scope.row.price)) }}
                </template>
              </el-table-column>
              <el-table-column prop="sumMoney" label="调拨金额" width="120">
                <template #default="scope">
                  ¥{{ formatAmount(scope.row.sumMoney) }}
                </template>
              </el-table-column>
              <el-table-column prop="outboundStatus" label="出库状态" width="100">
                <template #default="scope">
                  <el-tag :type="getOutboundStatusType(scope.row.outboundStatus)">
                    {{ scope.row.outboundStatus }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="出库记录" name="outbound">
          <div class="tab-content">
            <div class="table-header">
              <el-button type="info" @click="handleExportOutbound" class="export-btn">
                <el-icon><Download /></el-icon>
                导出
              </el-button>
            </div>
            
            <el-table
              :data="outboundRecords"
              style="width: 100%"
              border
              stripe
              class="detail-table"
              :summary-method="getOutboundSummary"
              show-summary
            >
              <el-table-column type="selection" width="55" />
              <el-table-column label="序号" width="60">
                <template #default="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="warehouse_Code" label="出库单号" width="120">
                <template #default="scope">
                  <span style="color: #67c23a;">{{ scope.row.warehouse_Code }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="reviewTime" label="出库日期" width="120">
                <template #default="scope">
                  {{ formatDate(scope.row.reviewTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="warehouse_Name" label="仓库名称" width="120" />
              <el-table-column prop="product_Name" label="出库货品" width="200" />
              <el-table-column prop="warehouse_InOrOutCount" label="出库数量" width="100" />
              <el-table-column prop="total_Price" label="出库金额" width="120">
                <template #default="scope">
                  ¥{{ formatAmount(scope.row.total_Price) }}
                </template>
              </el-table-column>
              <el-table-column prop="reviewer" label="经办人" width="100" />
              <el-table-column prop="creatorName" label="制单人" width="100" />
              <el-table-column prop="createTime" label="制单时间" width="150">
                <template #default="scope">
                  {{ formatDateTime(scope.row.createTime) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="入库记录" name="inbound">
          <div class="tab-content">
            <div class="table-header">
              <el-button type="info" @click="handleExport" class="export-btn">
                <el-icon><Download /></el-icon>
                导出
              </el-button>
            </div>
            
            <el-table
              :data="inboundRecords"
              style="width: 100%"
              border
              stripe
              class="detail-table"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column label="序号" width="60">
                <template #default="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="warehouse_Code" label="入库单号" width="120" />
              <el-table-column prop="reviewTime" label="入库日期" width="120">
                <template #default="scope">
                  {{ formatDate(scope.row.reviewTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="warehouse_Name" label="仓库名称" width="120" />
              <el-table-column prop="product_Name" label="入库货品" width="200" />
              <el-table-column prop="warehouse_InOrOutCount" label="入库数量" width="100" />
              <el-table-column prop="total_Price" label="入库金额" width="120">
                <template #default="scope">
                  ¥{{ formatAmount(scope.row.total_Price) }}
                </template>
              </el-table-column>
              <el-table-column prop="reviewer" label="经办人" width="100" />
              <el-table-column prop="creatorName" label="制单人" width="100" />
              <el-table-column prop="createTime" label="制单时间" width="150">
                <template #default="scope">
                  {{ formatDateTime(scope.row.createTime) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="操作记录" name="operations">
          <div class="tab-content">
            <p>操作记录内容</p>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Box, 
  Upload, 
  Download, 
  CopyDocument, 
  Printer
} from '@element-plus/icons-vue'
import { statementRed } from '@/http/axiosHelper'

const route = useRoute()
const router = useRouter()

// 响应式数据
const activeTab = ref('details')

// 订单信息
const orderInfo = reactive({
  movingCode: '',
  All_Id: '',
  creatorName: '',
  department_Name: '',
  createTime: '',
  allotWarehouseType: '',
  original_OutWarehouse: '',
  original_InWarehouse: '',
  reviewer: '',
  remarks: '',
  state: '',
  outState: '',
  inState: '',
  outCount: 0,
  inCount: 0,
  totalCount: 0
})

// 入库记录数据
const inboundRecords = ref<any[]>([])

// 调拨明细数据
const allocationDetails = ref<any[]>([])

// 出库记录数据
const outboundRecords = ref<any[]>([])

// 加载出库记录数据
const loadOutboundRecords = async (allId: string) => {
  try {
    console.log('加载出库记录，All_Id:', allId)
    
    // 调用API获取出库记录
    const response = await statementRed.get('/api/TwoWorkOrder/GetOutboundRecord', {
      params: {
        All_Id: allId
      }
    })
    
    console.log('出库记录API响应:', response)
    console.log('出库记录API响应状态码:', response.data.code)
    console.log('出库记录API响应数据:', response.data.data)
    
    if (response.data.code === 200) {
      outboundRecords.value = response.data.data || []
      console.log('出库记录已更新:', response.data.data)
      console.log('出库记录数组长度:', outboundRecords.value.length)
      console.log('出库记录数据:', outboundRecords.value)
    } else {
      console.error('出库记录API返回错误:', response.data.message)
      ElMessage.error(response.data.message || '获取出库记录失败')
    }
  } catch (error: any) {
    console.error('加载出库记录失败:', error)
    ElMessage.error('加载出库记录失败，请检查网络连接')
    
    // 使用模拟数据
    outboundRecords.value = [
      {
        warehouse_Code: 'CKDH3501',
        reviewTime: '2025-08-06',
        warehouse_Name: '仓库一',
        product_Name: '三锅头、可笑、何必等8项......',
        warehouse_InOrOutCount: 50,
        total_Price: 500.00,
        reviewer: '李晓明',
        creatorName: '李晓明',
        createTime: '2024-02-29T21:26:21'
      }
    ]
    console.log('使用模拟出库记录数据:', outboundRecords.value)
  }
}

// 加载入库记录数据
const loadInboundRecords = async (allId: string) => {
  try {
    console.log('加载入库记录，All_Id:', allId)
    
    // 调用API获取入库记录
    const response = await statementRed.get('/api/TwoWorkOrder/GetInboundRecord', {
      params: {
        All_Id: allId,
        warehouseType: 1  // 1表示入库
      }
    })
    
    console.log('入库记录API响应:', response)
    console.log('入库记录API响应状态码:', response.data.code)
    console.log('入库记录API响应数据:', response.data.data)
    
    if (response.data.code === 200) {
      inboundRecords.value = response.data.data || []
      console.log('入库记录已更新:', response.data.data)
      console.log('入库记录数组长度:', inboundRecords.value.length)
      console.log('入库记录数据:', inboundRecords.value)
    } else {
      console.error('入库记录API返回错误:', response.data.message)
      ElMessage.error(response.data.message || '获取入库记录失败')
    }
  } catch (error: any) {
    console.error('加载入库记录失败:', error)
    ElMessage.error('加载入库记录失败，请检查网络连接')
    
    // 使用模拟数据
    inboundRecords.value = [
      {
        warehouse_Code: 'RKDH3501',
        reviewTime: '2025-08-06',
        warehouse_Name: '仓库一',
        product_Name: '三锅头、可笑、何必等8项......',
        warehouse_InOrOutCount: 50,
        total_Price: 500.00,
        reviewer: '李晓明',
        creatorName: '李晓明',
        createTime: '2024-02-29T21:26:21'
      }
    ]
    console.log('使用模拟入库记录数据:', inboundRecords.value)
  }
}

// 加载调拨明细
const loadAllocationDetails = async (movingCode: string) => {
  try {

    
    // 调用API获取调拨明细
    const response = await statementRed.get('/api/TwoWorkOrder/GetAllotData', {
      params: {
        MovingCode: movingCode
      }
    })
    
    if (response.data.code === 200) {
      allocationDetails.value = response.data.data || []
    } else {
      console.error('API返回错误:', response.data.message)

    }
  } catch (error: any) {
    console.error('加载调拨明细失败:', error)
    ElMessage.error('加载调拨明细失败，请检查网络连接')
  
  }
}



// 监听调拨明细数据变化

// 获取路由参数
onMounted(async () => {
   console.log('=== 页面开始加载 ===');
   console.log('1');
  const movingCode = route.params.movingCode
  const dataParam = route.query.data as string
  
  console.log('movingCode:', movingCode);
  console.log('dataParam:', dataParam);
  
  if (movingCode && dataParam) {
    try {
      // 解码并解析传递的数据
      const decodedData = JSON.parse(decodeURIComponent(dataParam))
      console.log('接收到的数据:', decodedData)
      
      // 更新订单信息
      Object.assign(orderInfo, {
        movingCode: decodedData.movingCode || movingCode,
        All_Id: decodedData.All_Id || decodedData.all_Id || '',
        creatorName: decodedData.creatorName || '',
        department_Name: decodedData.department_Name || '',
        createTime: decodedData.createTime || '',
        allotWarehouseType: decodedData.allotWarehouseType || '',
        original_OutWarehouse: decodedData.original_OutWarehouse || '',
        original_InWarehouse: decodedData.original_InWarehouse || '',
        reviewer: decodedData.reviewer || '',
        remarks: decodedData.remarks || '',
        state: decodedData.state || '',
        outState: decodedData.outState || '',
        inState: decodedData.inState || '',
        outCount: decodedData.outCount || 0,
        inCount: decodedData.inCount || 0,
        totalCount: decodedData.totalCount || 0
      })
      
           
        
       // 加载调拨明细、出库记录和入库记录
      
      
         await loadAllocationDetails(movingCode as string)
         const allIdForQuery = orderInfo.All_Id || movingCode as string
         await loadOutboundRecords(allIdForQuery)
         await loadInboundRecords(allIdForQuery)
       
    } catch (error) {
      console.error('解析传递的数据失败:', error)
      ElMessage.error('数据解析失败')
    }
  } else {
    // 如果没有参数，使用默认数据
    console.log('使用默认数据')
  }
})

// 加载订单详情（已移除，直接从传递的数据中获取）

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString()
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 格式化金额
const formatAmount = (amount: number) => {
  return amount?.toFixed(2) || '0.00'
}

// 调出操作
const handleOutbound = () => {
  ElMessage.info('调出功能待实现')
}

// 调入操作
const handleInbound = () => {
  ElMessage.info('调入功能待实现')
}

// 复制操作
const handleCopy = () => {
  ElMessage.info('复制功能待实现')
}

// 打印操作
const handlePrint = () => {
  ElMessage.info('打印功能待实现')
}

// 导出入库操作
const handleExport = async () => {
  try {
    const allId = orderInfo.movingCode
    if (!allId) {
      ElMessage.error('调拨单号不存在')
      return
    }

    const response = await statementRed({
      url: '/api/TwoWorkOrder/GetInboundRecordExport',
      method: 'GET',
      params: {
        All_Id: allId
      },
      responseType: 'blob'
    })

    const fileName = getFileNameFromHeaders(response.headers, '入库记录表.xlsx')
    const blob = new Blob([response.data], {
      type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = fileName
    document.body.appendChild(a)
    a.click()
    window.URL.revokeObjectURL(url)
    document.body.removeChild(a)

    ElMessage.success('导出成功')
  } catch (error: any) {
    console.error('导出入库记录失败:', error)
    ElMessage.error('导出失败，请稍后重试')
  }
}

// 导出调拨明细
const handleExportDetails = async () => {
  try {
    const movingCode = orderInfo.movingCode
    if (!movingCode) {
      ElMessage.error('调拨单号不存在')
      return
    }

    console.log('开始导出调拨明细，MovingCode:', movingCode)

    const response = await statementRed({
      url: '/api/TwoWorkOrder/GetAllotDataExport',
      method: 'GET',
      params: {
        MovingCode: movingCode
      },
      responseType: 'blob'
    })

    console.log('调拨明细导出响应:', response)

    // 检查响应状态
    if (response.status !== 200) {
      throw new Error(`HTTP错误: ${response.status}`)
    }

    // 获取文件名
    const fileName = getFileNameFromHeaders(response.headers) || `调拨明细_${movingCode}_${new Date().toISOString().split('T')[0]}.xlsx`
    
    // 创建Blob对象
    const blob = new Blob([response.data], {
      type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })

    // 检查Blob大小
    if (blob.size === 0) {
      ElMessage.warning('导出的文件为空，请检查数据')
      return
    }

    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = fileName
    a.style.display = 'none'
    
    // 添加到DOM并触发下载
    document.body.appendChild(a)
    a.click()
    
    // 清理资源
    setTimeout(() => {
      window.URL.revokeObjectURL(url)
      document.body.removeChild(a)
    }, 100)

    ElMessage.success('调拨明细导出成功')
    console.log('调拨明细导出完成，文件名:', fileName)
  } catch (error: any) {
    console.error('导出调拨明细失败:', error)
    
    // 根据错误类型提供不同的错误信息
    if (error.response) {
      // 服务器响应错误
      if (error.response.status === 404) {
        ElMessage.error('导出接口不存在，请联系管理员')
      } else if (error.response.status === 401) {
        ElMessage.error('登录已过期，请重新登录')
      } else if (error.response.status === 403) {
        ElMessage.error('没有导出权限')
      } else {
        ElMessage.error(`导出失败: ${error.response.data?.message || '服务器错误'}`)
      }
    } else if (error.request) {
      // 网络错误
      ElMessage.error('网络连接失败，请检查网络设置')
    } else {
      // 其他错误
      ElMessage.error('导出失败，请稍后重试')
    }
  }
}

// 表格汇总方法
const getSummary = (param: any) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (index === 7) { // 调拨种类
      sums[index] = allocationDetails.value.length.toString()
      return
    }
    if (index === 8) { // 调拨数量
      const values = data.map((item: any) => Number(item.allotCount))
      if (!values.every((value: number) => isNaN(value))) {
        sums[index] = values.reduce((prev: number, curr: number) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0).toString()
      } else {
        sums[index] = '0'
      }
      return
    }
    if (index === 10) { // 调拨金额
      const values = data.map((item: any) => Number(item.sumMoney))
      if (!values.every((value: number) => isNaN(value))) {
        sums[index] = values.reduce((prev: number, curr: number) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0).toFixed(2)
      } else {
        sums[index] = '0.00'
      }
      return
    }
    sums[index] = ''
  })
  return sums
}

// 获取出库状态标签类型
const getOutboundStatusType = (status: string) => {
  const statusMap: { [key: string]: string } = {
    '未出': 'info',
    '部分出库': 'warning',
    '已出库': 'success'
  }
  return statusMap[status] || 'info'
}



// 出库记录汇总方法
const getOutboundSummary = (param: any) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (index === 6) { // 出库数量
      const values = data.map((item: any) => Number(item.warehouse_InOrOutCount))
      if (!values.every((value: number) => isNaN(value))) {
        sums[index] = values.reduce((prev: number, curr: number) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0).toString()
      } else {
        sums[index] = '0'
      }
      return
    }
    if (index === 7) { // 出库金额
      const values = data.map((item: any) => Number(item.total_Price))
      if (!values.every((value: number) => isNaN(value))) {
        sums[index] = values.reduce((prev: number, curr: number) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0).toFixed(2)
      } else {
        sums[index] = '0.00'
      }
      return
    }
    sums[index] = ''
  })
  return sums
}

// 导出出库记录
const handleExportOutbound = async () => {
  try {
    const allId = orderInfo.movingCode
    if (!allId) {
      ElMessage.error('调拨单号不存在')
      return
    }

    const response = await statementRed({
      url: '/api/TwoWorkOrder/GetOutboundRecordExport',
      method: 'GET',
      params: {
        All_Id: allId
      },
      responseType: 'blob'
    })

    const fileName = getFileNameFromHeaders(response.headers, '出库记录表.xlsx')
    const blob = new Blob([response.data], {
      type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = fileName
    document.body.appendChild(a)
    a.click()
    window.URL.revokeObjectURL(url)
    document.body.removeChild(a)

    ElMessage.success('导出成功')
  } catch (error: any) {
    console.error('导出出库记录失败:', error)
    ElMessage.error('导出失败，请稍后重试')
  }
}

// 从响应头获取文件名
const getFileNameFromHeaders = (headers: any, defaultFileName: string = '导出文件.xlsx') => {
  try {
    // 获取Content-Disposition头
    const contentDisposition = headers['content-disposition'] || headers['Content-Disposition']
    
    if (!contentDisposition) {
      console.log('未找到Content-Disposition头，使用默认文件名:', defaultFileName)
      return defaultFileName
    }

    console.log('Content-Disposition头:', contentDisposition)

    // 尝试多种文件名提取模式
    let fileName = null

    // 模式1: filename*=UTF-8''filename.ext
    const match1 = contentDisposition.match(/filename\*=UTF-8''([^;]+)/)
    if (match1) {
      fileName = decodeURIComponent(match1[1])
      console.log('模式1匹配成功:', fileName)
    }

    // 模式2: filename="filename.ext"
    if (!fileName) {
      const match2 = contentDisposition.match(/filename="([^"]+)"/)
      if (match2) {
        fileName = match2[1]
        console.log('模式2匹配成功:', fileName)
      }
    }

    // 模式3: filename=filename.ext
    if (!fileName) {
      const match3 = contentDisposition.match(/filename=([^;]+)/)
      if (match3) {
        fileName = match3[1]
        console.log('模式3匹配成功:', fileName)
      }
    }

    // 如果提取到文件名，进行URL解码
    if (fileName) {
      try {
        fileName = decodeURIComponent(fileName)
        console.log('解码后的文件名:', fileName)
        return fileName
      } catch (decodeError) {
        console.warn('文件名解码失败，使用原始文件名:', fileName)
        return fileName
      }
    }

    console.log('未能从Content-Disposition提取文件名，使用默认文件名:', defaultFileName)
    return defaultFileName
  } catch (error) {
    console.error('获取文件名时发生错误:', error)
    return defaultFileName
  }
}





</script>

<style scoped>
.allot-detail-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  padding: 20px;
}

.page-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 24px 32px;
  margin-bottom: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  font-size: 32px;
  color: #409eff;
  background: linear-gradient(135deg, #409eff, #67c23a);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0;
  background: linear-gradient(135deg, #409eff, #67c23a);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.header-right {
  display: flex;
  gap: 12px;
}

.action-btn {
  padding: 8px 16px;
  border-radius: 8px;
  font-weight: 500;
}

.order-info-card,
.tabs-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  margin-bottom: 24px;
}

.order-info {
  padding: 20px;
}

.order-header {
  margin-bottom: 20px;
}

.order-title {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0;
}

.order-details {
  display: flex;
  gap: 40px;
}

.details-left {
  flex: 1;
}

.details-right {
  width: 300px;
}

.detail-row {
  display: flex;
  margin-bottom: 12px;
  align-items: center;
}

.label {
  width: 120px;
  font-weight: 600;
  color: #606266;
}

.value {
  flex: 1;
  color: #2c3e50;
}

.status-card {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e9ecef;
}

.status-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.status-item:last-child {
  margin-bottom: 0;
}

.status-label {
  width: 80px;
  font-weight: 600;
  color: #606266;
}

.status-value {
  flex: 1;
  font-weight: 600;
  color: #2c3e50;
}

.status-value.approved {
  color: #67c23a;
  font-size: 18px;
}

.status-count {
  margin-left: 8px;
  color: #909399;
  font-size: 14px;
}

.detail-tabs {
  padding: 20px;
}

.tab-content {
  padding: 20px 0;
}

.table-header {
  margin-bottom: 20px;
}

.export-btn {
  padding: 8px 16px;
  border-radius: 8px;
}

.detail-table {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-tabs__item) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-tabs__item.is-active) {
  color: #409eff;
  font-weight: 600;
}

:deep(.el-tabs__active-bar) {
  background-color: #409eff;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #2c3e50;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
}
</style> 